package cn.hamster3.hamsterworld.command;

import cn.hamster3.hamsterworld.core.DataManager;
import cn.hamster3.hamsterworld.core.Message;
import cn.hamster3.hamsterworld.data.WorldData;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import java.util.ArrayList;
import java.util.List;

public class PublicCommand extends CommandBase {
    public PublicCommand(DataManager dataManager) {
        super(dataManager);
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        Player player = (Player) sender;
        WorldData data = dataManager.getWorldData(player);
        if (data == null) {
            player.sendMessage(Message.notHasWorld.toString());
            return true;
        }
        boolean isPublic = !data.isPublic();
        if (args.length >= 2) {
            String flag = args[1];
            switch (flag.toLowerCase()) {
                case "true":
                case "on":
                case "open":
                    isPublic = true;
                    break;
                case "false":
                case "off":
                case "close":
                default:
                    isPublic = false;
            }
        }
        data.setPublic(isPublic);
        if (isPublic) {
            sender.sendMessage(Message.setPublicOn.toString());
        } else {
            sender.sendMessage(Message.setPublicOff.toString());
            for (Player worldPlayer : data.getWorld().getPlayers()) {
                if (data.isAllowed(worldPlayer)) {
                    continue;
                }
                worldPlayer.teleport(Bukkit.getWorlds().get(0).getSpawnLocation());
                worldPlayer.sendMessage(Message.kickPlayer.toString().replace("%player%", sender.getName()));
            }
        }
        return true;
    }

    @Override
    public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
        ArrayList<String> tab = new ArrayList<>();
        for (String s : new String[]{"on", "off"}) {
            if (!s.startsWith(args[1].toLowerCase())) {
                continue;
            }
            tab.add(s);
        }
        return tab;
    }
}
